package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/http"
	"os"
	"path/filepath"
	"share/api/params"
	"share/golbal"
	"share/model"
	"share/pkg"
)

func Upload(c *gin.Context) {

	file, err := c.FormFile("image")
	if err != nil {
		return
	}
	s := uuid.NewString() + ".png"
	err = c.SaveUploadedFile(file, "./"+s)
	if err != nil {
		return
	}
	if file.Size > 200*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "图片大小不超过200KB",
		})
		return
	}

	ext := filepath.Ext(file.Filename)
	if ext != ".jpg" && ext != ".png" && ext != "gif" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "只允许上传jpg,png,gif格式",
		})
		return
	}
	get, err := os.Getwd()

	upload, err := pkg.Upload(get + "/" + s)
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "图片上传成功",
		"data": upload,
	})
}

func PostAdd(c *gin.Context) {
	add := params.PostReq{}
	if err := c.ShouldBind(&add); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	post := model.Post{

		UserId:  add.UserId,
		Content: add.Content,
		Status:  add.Status,
	}
	golbal.DB.Debug().Create(&post)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "帖子发布成功",
	})
}

func PostDelete(c *gin.Context) {
	add := params.PostDelReq{}
	if err := c.ShouldBind(&add); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var post model.Post

	golbal.DB.Debug().Where("id=?", post.ID).Delete(&model.Post{})
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "帖子删除成功",
	})

}

func PostShow(c *gin.Context) {
	add := params.PosShowReq{}
	if err := c.ShouldBind(&add); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var post model.Post

	m := model.Post{
		Model:   gorm.Model{ID: post.ID},
		UserId:  post.UserId,
		Content: post.Content,
		Status:  post.Status,
	}
	golbal.DB.Debug().Where("id=?", post.ID).Find(&m)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "帖子详情查看成功",
		"data": add,
	})

}

func PostList(c *gin.Context) {
	list := params.PosShowListReq{}
	if err := c.ShouldBind(&list); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	page := list.Page
	if page <= 0 {
		page = 1
	}

	pageSize := list.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	golbal.DB.Debug().Where(offset).Limit(list.Size).Find(&list)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "帖子列表查询成功",
		"data": list,
	})

}
